﻿using Application.Service;

using Furion;

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

using SqlSugar;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Application.Test
{
	public class Startup : AppStartup
	{
		public void ConfigureServices(IServiceCollection services)
		{
			// 注册远程服务
			services.AddHttpRemote();

			// 注册 SQLSugar（Sqlite）并规范化 Data Source 路径
			services.AddSingleton<ISqlSugarClient>(sp =>
			{
				var env = sp.GetRequiredService<IHostEnvironment>();

				// 从 appsettings.json 读取 connection 节点内容
				var conn = App.GetConfig<string>("ConnectionConfigs:ConnectionString");// builder.Configuration["connection"];

				var normalized = DbService.NormalizeSqliteConnectionString(conn, env.ContentRootPath,true);

				return new SqlSugarScope(new ConnectionConfig
				{
					ConnectionString = normalized,
					DbType = DbType.Sqlite,
					IsAutoCloseConnection = true,
					InitKeyType = InitKeyType.Attribute
				},
				db =>
				{
					// 可选：SQL 输出
					db.Aop.OnLogExecuting = (sql, pars) =>
					{
						//System.Console.WriteLine(UtilMethods.GetSqlString(DbType.Sqlite, sql, pars));
					};
				});
			});
		}

		public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
		{
			// 启动时初始化表结构
			using (var scope = app.ApplicationServices.CreateScope())
			{
				var db = scope.ServiceProvider.GetRequiredService<ISqlSugarClient>();
				// 创建数据库（Sqlite）若不存在
				var created = DbService.CreateDBFile(db);
				// 如需按实体自动建表，取消注释并替换为实际实体类型：
				// DbContext.Instance.CodeFirst.InitTables(typeof(YourEntity1), typeof(YourEntity2));

				// 反射扫描所有带有 [SugarTable] 特性的实体类型
				var modelTypes = AppDomain.CurrentDomain.GetAssemblies()
					.Where(a => !a.IsDynamic
						&& !a.FullName.StartsWith("System.", StringComparison.OrdinalIgnoreCase)
						&& !a.FullName.StartsWith("Microsoft.", StringComparison.OrdinalIgnoreCase)
						&& !a.FullName.StartsWith("netstandard", StringComparison.OrdinalIgnoreCase))
					.SelectMany(a =>
					{
						try { return a.GetExportedTypes(); }
						catch { return Type.EmptyTypes; }
					})
					.Where(t => t.IsClass && !t.IsAbstract && t.GetCustomAttributes(typeof(SugarTable), inherit: true).Any())
					.ToArray();

				// 根据实体类型创建表（存在则不创建）
				if (modelTypes.Length > 0)
				{
					db.CodeFirst.InitTables(modelTypes);
				}
				//if (created == 1)
				//{
				//	//新增User、Permission、UserPermission种子数据
				//	//DbService.SeedDataCommit(db);
				//}
			}
		}
	}
}
